package com.selfdiscipline.ui.screens.habit

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.selfdiscipline.data.local.entity.HabitEntity
import com.selfdiscipline.domain.repository.HabitRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.time.LocalDate
import javax.inject.Inject

/**
 * 习惯详情UI状态
 */
data class HabitDetailUiState(
    val habit: HabitEntity? = null,
    val isLoading: Boolean = false,
    val error: String? = null
)

@HiltViewModel
class HabitDetailViewModel @Inject constructor(
    private val habitRepository: HabitRepository
) : ViewModel() {

    private val _uiState = MutableStateFlow(HabitDetailUiState())
    val uiState: StateFlow<HabitDetailUiState> = _uiState.asStateFlow()

    fun loadHabit(habitId: Long) {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true) }
            
            try {
                val habit = habitRepository.getHabitById(habitId)
                _uiState.update { 
                    it.copy(
                        habit = habit,
                        isLoading = false
                    )
                }
            } catch (e: Exception) {
                _uiState.update { 
                    it.copy(
                        isLoading = false,
                        error = e.message
                    )
                }
            }
        }
    }

    fun completeHabit(habitId: Long) {
        viewModelScope.launch {
            val habit = habitRepository.getHabitById(habitId) ?: return@launch
            val today = LocalDate.now()
            
            // 只有今天还没完成的习惯才能标记为完成
            if (habit.lastCompletedDate != today) {
                habitRepository.completeHabit(habitId, today)
                
                // 重新加载习惯数据
                loadHabit(habitId)
            }
        }
    }
    
    fun deleteHabit(habitId: Long) {
        viewModelScope.launch {
            habitRepository.deleteHabitById(habitId)
        }
    }
} 